package com.alvis.media.controller;

import com.alvis.media.base.BaseApiController;
import com.alvis.media.base.NonStaticResourceHttpRequestHandler;
import com.alvis.media.base.RestResponse;
import com.alvis.media.domain.User;
import com.alvis.media.domain.VideoInfo;
import com.alvis.media.domain.VideoPlay;
import com.alvis.media.service.VideoService;
import com.alvis.media.utility.DateTimeUtil;
import com.alvis.media.utility.PageInfoHelper;
import com.alvis.media.viewmodel.video.*;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController("VideoController")
@RequestMapping(value = "/api/admin/video")
@AllArgsConstructor
public class VideoController  extends BaseApiController
{
    // DI/IoC
    @Autowired
    private VideoService videoService;

    @Autowired
    private NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

    /**
     * 视频播放 - 支持范围请求和断点续播
     */
    @GetMapping("/play/**/*")
    public void playVideo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //realPath 即视频所在的完整地址
        String url = request.getRequestURL().toString();
        int index=  url.lastIndexOf("D:");
        String realPath = url.substring(index);

        Path filePath = Paths.get(realPath);
        if (Files.exists(filePath)) {
            // 利用 Files.probeContentType 获取文件类型
            String mimeType = Files.probeContentType(filePath);
            if (!StringUtils.isEmpty(mimeType)) {
                // 设置 response
                response.setContentType(mimeType);
            }
            request.setAttribute(nonStaticResourceHttpRequestHandler.filepath, filePath);
            // 利用 ResourceHttpRequestHandler.handlerRequest() 实现返回视频流
            nonStaticResourceHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }



    /**
     * 视频列表 - 分页查询
     */
    @RequestMapping(value = "/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<VideoResponseVM>> pageList(@RequestBody VideoPageRequestVM model) {
        PageInfo<VideoInfo> pageInfo = videoService.videoPage(model);
        PageInfo<VideoResponseVM> page = PageInfoHelper.copyMap(pageInfo, d -> VideoResponseVM.from(d));
        return RestResponse.ok(page);
    }


    /**
     * 添加视频
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> createVideo(@RequestBody @Valid VideoCreateVM model) {
        try {
            // 校验视频URL
            String videoURL = model.getVideoUrl();
            if (StringUtils.isBlank(videoURL)) {
                return RestResponse.fail(400, "视频文件未上传");
            }
            
            // 校验视频分类
            if (model.getVideoCategory() == null) {
                return RestResponse.fail(400, "请选择视频分类");
            }
            
            // 校验视频名称
            if (StringUtils.isBlank(model.getVideoName())) {
                return RestResponse.fail(400, "视频名称不能为空");
            }
            
            User currentUser = getCurrentUser();
            if (currentUser == null) {
                return RestResponse.fail(401, "用户未登录");
            }
            
            VideoInfo videoInfo = modelMapper.map(model, VideoInfo.class);
            videoInfo.setCreatorId(currentUser.getId());
            videoInfo.setVideoCategory(model.getVideoCategory());
            videoInfo.setVideoName(model.getVideoName());
            videoInfo.setCreateTime(new Date());
            
            // 生成新的视频URL（按日期组织）
            String newVideoUrl = DateTimeUtil.getCurrentTimeYMD() + 
                    StringUtils.substring(videoURL, StringUtils.lastIndexOf(videoURL, "/"));
            videoInfo.setVideoUrl(newVideoUrl);
            
            videoService.insertByFilter(videoInfo);
            
            log.info("添加视频成功: videoId={}, videoName={}, creator={}", 
                    videoInfo.getVideoId(), videoInfo.getVideoName(), currentUser.getUserName());
            
            return RestResponse.ok();
            
        } catch (Exception e) {
            log.error("添加视频异常", e);
            return RestResponse.fail(500, "添加视频失败: " + e.getMessage());
        }
    }

    /**
     * 查询视频信息
     */
    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> select(@PathVariable Integer id) {
        try {
            VideoInfo video = videoService.getVideoById(id);
            if (video == null) {
                return RestResponse.fail(404, "视频不存在");
            }
            return RestResponse.ok(VideoResponseVM.from(video));
        } catch (Exception e) {
            log.error("查询视频信息异常: videoId={}", id, e);
            return RestResponse.fail(500, "查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取视频详情
     */
    @RequestMapping(value = "/getVideoDetailByVideoId/{id}", method = RequestMethod.POST)
    public RestResponse<VideoDetailVM> getVideoDetailByVideoId(@PathVariable Integer id) {
        try {
            // 获取视频基本信息
            VideoInfo videoInfo = videoService.getVideoById(id);
            if (videoInfo == null) {
                return RestResponse.fail(404, "视频不存在");
            }
            VideoDetailVM vm = new VideoDetailVM();
            vm.setVideoId(videoInfo.getVideoId());
            vm.setVideoName(videoInfo.getVideoName());
            
            log.info("获取视频详情成功: videoId={}", id);
            return RestResponse.ok(vm);
            
        } catch (Exception e) {
            log.error("获取视频详情异常: videoId={}", id, e);
            return RestResponse.fail(500, "获取视频详情失败: " + e.getMessage());
        }
    }


    /**
     * 编辑视频
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> editVideo(@RequestBody @Valid VideoCreateVM model) {
        try {
            Integer videoId = model.getVideoId();
            if (videoId == null) {
                return RestResponse.fail(400, "视频ID不能为空");
            }
            
            // 检查视频是否存在
            VideoInfo existingVideo = videoService.getVideoById(videoId);
            if (existingVideo == null) {
                return RestResponse.fail(404, "视频不存在");
            }
            
            VideoInfo videoInfo = modelMapper.map(model, VideoInfo.class);
            videoInfo.setVideoId(videoId);
            videoInfo.setVideoName(model.getVideoName());
            videoInfo.setVideoCategory(model.getVideoCategory());
            videoInfo.setLastModifyTime(new Date());
            
            int updateCount = videoService.updateByIdFilter(videoInfo);
            if (updateCount <= 0) {
                return RestResponse.fail(500, "编辑视频失败，请重试");
            }
            
            log.info("编辑视频成功: videoId={}, videoName={}", videoId, model.getVideoName());
            return RestResponse.ok();
            
        } catch (Exception e) {
            log.error("编辑视频异常: videoId={}", model.getVideoId(), e);
            return RestResponse.fail(500, "编辑失败: " + e.getMessage());
        }
    }

    /**
     * 删除视频
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        try {
            VideoInfo videoInfo = videoService.selectById(id);
            if (videoInfo == null) {
                return RestResponse.fail(404, "该视频不存在");
            }
            
            int updateCount = videoService.deleteById(id);
            if (updateCount <= 0) {
                return RestResponse.fail(500, "删除视频失败，请重试");
            }
            
            log.info("删除视频成功: videoId={}, videoName={}", id, videoInfo.getVideoName());
            return RestResponse.ok("视频删除成功");
            
        } catch (Exception e) {
            log.error("删除视频异常: videoId={}", id, e);
            return RestResponse.fail(500, "删除失败: " + e.getMessage());
        }
    }


    @RequestMapping(value = "/userAnalysis/{id}", method = RequestMethod.POST)
    public RestResponse <UserAnalysisVM> userAnalysis(@PathVariable Integer id) {

        return null;
    }
}
